import React from "react";
import { RegisterSchema, TRegisterSchema } from "@/schemas";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, type SubmitHandler } from "react-hook-form";

import { Button } from "@/components/ui/button";

import { Input } from "@/components/ui/input";
import { api } from "@/trpc/react";

const Register = ({ children }: { children: React.ReactNode }) => {
  const form = useForm<TRegisterSchema>({
    resolver: zodResolver(RegisterSchema),
    defaultValues: {
      email: "",
      password: "",
      rePassword: "",
    },
  });
  const m = api.post.register.useMutation();

  const onSubmit: SubmitHandler<TRegisterSchema> = async (data) => {
    m.mutate({
      email: data.email,
      password: data.password,
      rePassword: data.rePassword,
    });
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>邮箱</FormLabel>
              <FormControl>
                <Input
                  autoComplete="off"
                  type="email"
                  placeholder="请输入邮箱"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <FormLabel>密码</FormLabel>
              <FormControl>
                <Input type="password" placeholder="请输入密码" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="rePassword"
          render={({ field }) => (
            <FormItem>
              <FormLabel>重复密码</FormLabel>
              <FormControl>
                <Input
                  type="password"
                  placeholder="请输入重复密码"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit" className="w-full">
          注册
        </Button>
        <FormDescription className="text-center">{children}</FormDescription>
      </form>
    </Form>
  );
};

export default Register;
